const Service = require('../models/Service');
const Order = require('../models/Order');
const catchAsync = require('../utils/catchAsync');
const AppError = require('../utils/appError');
const APIFeatures = require('../utils/apiFeatures');
const { validationResult } = require('express-validator');
const multer = require('multer');
const sharp = require('sharp');
const path = require('path');
const fs = require('fs').promises;

// 配置 multer 用于文件上传
const multerStorage = multer.memoryStorage();

const multerFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image')) {
    cb(null, true);
  } else {
    cb(new AppError('请上传图片文件', 400), false);
  }
};

const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
});

// 上传服务图片
exports.uploadServiceImages = upload.fields([
  { name: 'icon', maxCount: 1 },
  { name: 'images', maxCount: 5 }
]);

// 处理服务图片
exports.processServiceImages = catchAsync(async (req, res, next) => {
  if (!req.files) return next();

  // 处理图标
  if (req.files.icon) {
    const iconFilename = `service-icon-${req.body.slug || Date.now()}-${Date.now()}.jpeg`;
    const iconPath = path.join('public', 'img', 'services', 'icons', iconFilename);

    // 确保目录存在
    await fs.mkdir(path.dirname(iconPath), { recursive: true });

    await sharp(req.files.icon[0].buffer)
      .resize(64, 64)
      .toFormat('jpeg')
      .jpeg({ quality: 90 })
      .toFile(iconPath);

    req.body.icon = iconFilename;
  }

  // 处理服务图片
  if (req.files.images) {
    req.body.images = [];

    await Promise.all(
      req.files.images.map(async (file, i) => {
        const filename = `service-${req.body.slug || Date.now()}-${i + 1}-${Date.now()}.jpeg`;
        const filepath = path.join('public', 'img', 'services', filename);

        // 确保目录存在
        await fs.mkdir(path.dirname(filepath), { recursive: true });

        await sharp(file.buffer)
          .resize(800, 600)
          .toFormat('jpeg')
          .jpeg({ quality: 90 })
          .toFile(filepath);

        req.body.images.push(filename);
      })
    );
  }

  next();
});

// 获取所有服务
exports.getAllServices = catchAsync(async (req, res, next) => {
  const features = new APIFeatures(Service.find({ status: 'active' }), req.query)
    .filter()
    .sort()
    .limitFields()
    .paginate();

  const services = await features.query;
  const total = await Service.countDocuments({ status: 'active' });

  res.status(200).json({
    status: 'success',
    results: services.length,
    total,
    data: {
      services
    }
  });
});

// 获取单个服务
exports.getService = catchAsync(async (req, res, next) => {
  const service = await Service.findOne({
    $or: [
      { _id: req.params.id },
      { slug: req.params.id }
    ],
    status: 'active'
  });

  if (!service) {
    return next(new AppError('服务不存在', 404));
  }

  res.status(200).json({
    status: 'success',
    data: {
      service
    }
  });
});

// 搜索服务
exports.searchServices = catchAsync(async (req, res, next) => {
  const {
    category,
    petTypes,
    location,
    duration,
    minPrice,
    maxPrice,
    requiresSpecialSkills,
    isEmergencyService,
    keyword
  } = req.query;

  // 构建查询条件
  let query = {
    status: 'active'
  };

  // 分类筛选
  if (category) {
    query.category = category;
  }

  // 宠物类型筛选
  if (petTypes) {
    const petTypeArray = petTypes.split(',');
    query.applicablePetTypes = { $in: petTypeArray };
  }

  // 服务地点筛选
  if (location) {
    query['characteristics.location'] = location;
  }

  // 时长筛选
  if (duration) {
    const [min, max] = duration.split('-').map(Number);
    if (min && max) {
      query['characteristics.duration.min'] = { $lte: max };
      query['characteristics.duration.max'] = { $gte: min };
    }
  }

  // 价格筛选
  if (minPrice || maxPrice) {
    query['pricing.basePrice'] = {};
    if (minPrice) query['pricing.basePrice'].$gte = Number(minPrice);
    if (maxPrice) query['pricing.basePrice'].$lte = Number(maxPrice);
  }

  // 特殊技能要求
  if (requiresSpecialSkills === 'true') {
    query['characteristics.requiresSpecialSkills'] = true;
  }

  // 紧急服务
  if (isEmergencyService === 'true') {
    query['characteristics.isEmergencyService'] = true;
  }

  // 关键词搜索
  if (keyword) {
    query.$or = [
      { name: { $regex: keyword, $options: 'i' } },
      { 'description.short': { $regex: keyword, $options: 'i' } },
      { 'description.detailed': { $regex: keyword, $options: 'i' } },
      { tags: { $in: [new RegExp(keyword, 'i')] } },
      { searchKeywords: { $in: [new RegExp(keyword, 'i')] } }
    ];
  }

  const features = new APIFeatures(Service.find(query), req.query)
    .sort('-stats.popularityScore -stats.averageRating')
    .limitFields()
    .paginate();

  const services = await features.query;

  res.status(200).json({
    status: 'success',
    results: services.length,
    data: {
      services
    }
  });
});

// 获取服务分类
exports.getServiceCategories = catchAsync(async (req, res, next) => {
  const categories = await Service.aggregate([
    { $match: { status: 'active' } },
    {
      $group: {
        _id: '$category',
        count: { $sum: 1 },
        averagePrice: { $avg: '$pricing.basePrice' },
        services: {
          $push: {
            _id: '$_id',
            name: '$name',
            slug: '$slug',
            icon: '$icon'
          }
        }
      }
    },
    { $sort: { count: -1 } }
  ]);

  res.status(200).json({
    status: 'success',
    data: {
      categories
    }
  });
});

// 获取热门服务
exports.getPopularServices = catchAsync(async (req, res, next) => {
  const { limit = 10 } = req.query;

  const services = await Service.find({ status: 'active' })
    .sort('-stats.popularityScore -stats.totalOrders')
    .limit(Number(limit))
    .select('name slug icon description.short pricing.basePrice stats');

  res.status(200).json({
    status: 'success',
    results: services.length,
    data: {
      services
    }
  });
});

// 创建服务（管理员功能）
exports.createService = catchAsync(async (req, res, next) => {
  // 检查验证错误
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return next(new AppError('输入数据验证失败', 400, errors.array()));
  }

  const service = await Service.create(req.body);

  res.status(201).json({
    status: 'success',
    data: {
      service
    }
  });
});

// 更新服务（管理员功能）
exports.updateService = catchAsync(async (req, res, next) => {
  // 检查验证错误
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return next(new AppError('输入数据验证失败', 400, errors.array()));
  }

  const service = await Service.findByIdAndUpdate(
    req.params.id,
    req.body,
    { new: true, runValidators: true }
  );

  if (!service) {
    return next(new AppError('服务不存在', 404));
  }

  res.status(200).json({
    status: 'success',
    data: {
      service
    }
  });
});

// 删除服务（管理员功能）
exports.deleteService = catchAsync(async (req, res, next) => {
  const service = await Service.findById(req.params.id);

  if (!service) {
    return next(new AppError('服务不存在', 404));
  }

  // 检查是否有相关的订单
  const orderCount = await Order.countDocuments({ service: service._id });
  if (orderCount > 0) {
    // 软删除
    service.status = 'inactive';
    await service.save();
  } else {
    // 硬删除
    await Service.findByIdAndDelete(req.params.id);
  }

  res.status(204).json({
    status: 'success',
    data: null
  });
});

// 计算服务价格
exports.calculateServicePrice = catchAsync(async (req, res, next) => {
  const { serviceId, startDateTime, endDateTime, petCount = 1, isEmergency = false } = req.body;

  const service = await Service.findById(serviceId);
  if (!service) {
    return next(new AppError('服务不存在', 404));
  }

  const startDate = new Date(startDateTime);
  const endDate = new Date(endDateTime);
  
  const price = await service.calculatePrice({
    startDate,
    endDate,
    petCount,
    isEmergency
  });

  res.status(200).json({
    status: 'success',
    data: {
      pricing: price
    }
  });
});

// 获取服务统计信息（管理员功能）
exports.getServiceStats = catchAsync(async (req, res, next) => {
  const stats = await Service.aggregate([
    {
      $group: {
        _id: null,
        totalServices: { $sum: 1 },
        activeServices: {
          $sum: { $cond: [{ $eq: ['$status', 'active'] }, 1, 0] }
        },
        averagePrice: { $avg: '$pricing.basePrice' },
        totalOrders: { $sum: '$stats.totalOrders' },
        totalRevenue: { $sum: '$stats.totalRevenue' }
      }
    }
  ]);

  // 按分类统计
  const categoryStats = await Service.aggregate([
    { $match: { status: 'active' } },
    {
      $group: {
        _id: '$category',
        count: { $sum: 1 },
        averagePrice: { $avg: '$pricing.basePrice' },
        totalOrders: { $sum: '$stats.totalOrders' }
      }
    },
    { $sort: { count: -1 } }
  ]);

  // 按宠物类型统计
  const petTypeStats = await Service.aggregate([
    { $match: { status: 'active' } },
    { $unwind: '$applicablePetTypes' },
    {
      $group: {
        _id: '$applicablePetTypes',
        count: { $sum: 1 }
      }
    },
    { $sort: { count: -1 } }
  ]);

  // 最受欢迎的服务
  const popularServices = await Service.find({ status: 'active' })
    .sort('-stats.popularityScore')
    .limit(10)
    .select('name stats.totalOrders stats.averageRating stats.popularityScore');

  res.status(200).json({
    status: 'success',
    data: {
      overview: stats[0] || {},
      categoryDistribution: categoryStats,
      petTypeDistribution: petTypeStats,
      popularServices
    }
  });
});

// 更新服务状态（管理员功能）
exports.updateServiceStatus = catchAsync(async (req, res, next) => {
  const { status } = req.body;
  
  const service = await Service.findByIdAndUpdate(
    req.params.id,
    { status },
    { new: true }
  );

  if (!service) {
    return next(new AppError('服务不存在', 404));
  }

  res.status(200).json({
    status: 'success',
    data: {
      service
    }
  });
});

// 批量更新服务（管理员功能）
exports.bulkUpdateServices = catchAsync(async (req, res, next) => {
  const { serviceIds, updateData } = req.body;

  if (!serviceIds || !Array.isArray(serviceIds) || serviceIds.length === 0) {
    return next(new AppError('请提供要更新的服务ID列表', 400));
  }

  const result = await Service.updateMany(
    { _id: { $in: serviceIds } },
    updateData,
    { runValidators: true }
  );

  res.status(200).json({
    status: 'success',
    data: {
      modifiedCount: result.modifiedCount,
      matchedCount: result.matchedCount
    }
  });
});

// 获取服务评价
exports.getServiceReviews = catchAsync(async (req, res, next) => {
  const { page = 1, limit = 10, rating } = req.query;
  
  let matchCondition = {
    service: req.params.id,
    'reviews.customer': { $exists: true }
  };

  if (rating) {
    matchCondition['reviews.customer.rating'] = Number(rating);
  }

  const reviews = await Order.aggregate([
    { $match: matchCondition },
    { $unwind: '$reviews' },
    { $match: { 'reviews.reviewType': 'customer' } },
    {
      $lookup: {
        from: 'users',
        localField: 'reviews.reviewer',
        foreignField: '_id',
        as: 'reviewer'
      }
    },
    { $unwind: '$reviewer' },
    {
      $project: {
        rating: '$reviews.rating',
        comment: '$reviews.comment',
        createdAt: '$reviews.createdAt',
        reviewer: {
          name: '$reviewer.name',
          avatar: '$reviewer.avatar'
        }
      }
    },
    { $sort: { createdAt: -1 } },
    { $skip: (page - 1) * limit },
    { $limit: Number(limit) }
  ]);

  const totalReviews = await Order.countDocuments(matchCondition);

  res.status(200).json({
    status: 'success',
    results: reviews.length,
    total: totalReviews,
    data: {
      reviews
    }
  });
});

// 获取推荐服务
exports.getRecommendedServices = catchAsync(async (req, res, next) => {
  const { petTypes, location, priceRange } = req.query;
  const { limit = 5 } = req.query;

  let query = { status: 'active' };

  // 根据用户的宠物类型推荐
  if (petTypes) {
    const petTypeArray = petTypes.split(',');
    query.applicablePetTypes = { $in: petTypeArray };
  }

  // 根据价格范围推荐
  if (priceRange) {
    const [min, max] = priceRange.split('-').map(Number);
    if (min && max) {
      query['pricing.basePrice'] = { $gte: min, $lte: max };
    }
  }

  const services = await Service.find(query)
    .sort('-stats.popularityScore -stats.averageRating')
    .limit(Number(limit))
    .select('name slug icon description.short pricing.basePrice stats');

  res.status(200).json({
    status: 'success',
    results: services.length,
    data: {
      services
    }
  });
});